/**
 * Fetch data for real balance in one month
 */
Ext.define('Cps.view.dashboard.ReportV2', {
	
	config: {
		params: {},
        panel: null //the panel to display
	},
	
	constructor: function(config) {
		if(config)
			this.initConfig(config);
	},
	
	/**
	 * Do load data with custom argument
	 * @param arg { success, fail }
	 */
	loadData: function() {
		Ext.Ajax.request({
	        method: 'GET',
	        url: Cps.Config.Api.reportv2,
	        params: this.getParams(),
	        success: this.success,
	        scope: this
	    });
	},
	
	renderField: function(data, meta, rec, row, col) {
		// renderer debit value, credit value
		if(!data)
			data = '';
		else {
			return Ext.util.Format.number(data, '0,000.00');
			/*data = parseFloat(data);
			var minus = data < 0;
			var f = '0,000';
			if(minus) {
				data = '-' + Ext.util.Format.number(-data, f);
			}
			else {
				data = Ext.util.Format.number(data, f);
			}*/
			
			if(col == 3) { //debit
				if(data.toLowerCase() == 'no')
					data = '&nbsp;';
				else {
					data = rec.get('entamount');
					data = parseFloat(data);
					var minus = data < 0;
					var f = '0,000.0';
					if(minus) {
						data = Ext.util.Format.number(-data, f);
					}
					else {
						data = Ext.util.Format.number(data, f);
					}
				}
			}
			else { //credit
				if(rec.get('entdebit').toLowerCase() == 'yes')
					data = '&nbsp;';
				else {
					data = parseFloat(data);
					var minus = data < 0;
					var f = '0,000.0';
					if(minus) {
						data = Ext.util.Format.number(-data, f);
					}
					else {
						data = Ext.util.Format.number(data, f);
					}
				}
			}
		}
		return data;
	},
	redererBalance: function(data, meta, rec, row, col){
        if(!data)
			data = '';
		else {
			str = data >= 0 ? Ext.util.Format.number(data, '0,000.00') : ('-' + Ext.util.Format.number(-data, '0,000.00'));
			data = (data > 0) ? ('<div style="text-align: right;font-weight: bold;color:blue">' + str + '</div>') : ('<div style="text-align: right;font-weight: bold;color:red">' + str + '</div>');
		}
		return data;
	},
	
	success: function(data) {
		data = Ext.JSON.decode(data.responseText).data;
        data = data ? data.ttCompte : null;
        data = data ? data.ttCompteRow : null;
		//build column
		var columns = [], fields = [];

        var f_data = [];
        if(data)
            for(i = 0; i < data.length; i++) {
                if(data[i].solde && data[i].solde != '0')
                    f_data.push(data[i]);
            }

		columns = [{//Compte
			text: '<b>' + Cps.Locale.ReportV2.company + '</b>',
			dataIndex: 'compte',
			flex: 2,
			//renderer: this.renderField,
			summaryType:    'count',
            summaryRenderer: function(value, summaryData, dataIndex) {
                return ((value === 0 || value > 1) ? '(' + value + ' ' + Cps.Locale.ReportV2.tasks + ')' : '(1 ' + Cps.Locale.ReportV2.task +')');
            },
			sortable:       true,
			groupable:      true,	
		},
		{//label
			text: '<b>' + Cps.Locale.ReportV2.label + '</b>',
			dataIndex: 'libelle',
			flex: 2,
			sortable:       true,
			groupable:      true,
			//renderer: this.renderField
		},
		{//currency
			text: '<b>' + Cps.Locale.ReportV2.currency + '</b>',
			dataIndex: 'monnaie',
			flex: 1,
			sortable:       true,
			groupable:      true,
			//renderer: this.renderField
		},
        {//balance
            text: '<b>' + Cps.Locale.ReportV2.balance + '</b>',
            dataIndex: 'solde',
            flex: 2,
			sortable:       true,
            groupable:      true,
            renderer: this.redererBalance,
            align: 'right',
            summaryType: 'sum',
            summaryRenderer: function(value, summaryData, dataIndex) {
                return '<div style="text-align: right;font-weight: bold">Total:</div>';
                str = value > 0 ? Ext.util.Format.number(value, '0,000.00') : Ext.util.Format.number(-value, '-0,000.00');
                return '<div style="text-align: right;font-weight: bold">' + str + '</div>';
            }
        },
		{//debit
			text: '<b>' + Cps.Locale.ReportV2.debit + '</b>',
			dataIndex: 'mntdeb',
			flex: 2,
			sortable:       true,
            groupable:      true,
			renderer: this.renderField,
			align: 'right',
			summaryType: 'sum',
	        summaryRenderer: function(value, summaryData, dataIndex) {
                str = value > 0 ? Ext.util.Format.number(value, '0,000.00') : Ext.util.Format.number(-value, '-0,000.00');
                return '<div style="text-align: right;font-weight: bold">' + str + ' EUR</div>';
	        	/*var sum = this.store.sum('entamount');
	            return sum > 0 ? '' : ('<div style="text-align: right;font-weight: bold">' + Ext.util.Format.number(-sum, '0,000.0') + '</div>');*/
	        }
		},
		{//credit
			text: '<b>' + Cps.Locale.ReportV2.credit + '</b>',
			dataIndex: 'mntcre',
			flex: 2,
			sortable:       true,
            groupable:      true,
			renderer: this.renderField,
			align: 'right',
			summaryType: 'sum',
			summaryRenderer: function(value, summaryData, dataIndex) {
                str = value > 0 ? Ext.util.Format.number(value, '0,000.00') : Ext.util.Format.number(-value, '-0,000.00');
				return '<div style="text-align: right;font-weight: bold">' + str + ' EUR</div>';
	        }
		}
		];

		fields = [
			{
				name: "compte",
				type: "string"
			},
			{
				name: "libelle",
				type: "string"
			},
			{
				name: "monnaie",
				type: "string"
			},
            {
                name: "debit",
                type: "bool"
            },
            {
                name: "solde",
                type: "number"
            },
			{
				name: "mntdeb",
				type: "number"
			},
			{
				name: "mntcre",
				type: "number"
			}
		];
		
		//create store
		var store = Ext.create('Ext.data.Store', {
			fields: fields,
			data: f_data
		});

		//do render data
		var grid = Ext.create('Ext.grid.Panel', {
			store: store,
			title: store.count() + ' ' + Cps.Locale.ReportV2.result,
			columns: columns,
		
			/*columnLines: true,
			viewConfig: {
	            stripeRows: true
	        },*/
			border: 0,
			features: [
				Ext.create('Ext.ux.grid.feature.MultiGroupingSummary', {
				id:                     'group',
				hideGroupedHeader:      true,
				enableGroupingMenu:     true,
				startCollapsed:         true
			}),{
		        ftype: 'summary',
			}
			],
			plugins: [
				Ext.create('Ext.ux.grid.plugin.GroupingPanel')
			],
			dockedItems: [
			{
				xtype: 'toolbar',
				dock: 'top',
				items: [
				{
					xtype: 'tbfill'
				},{
					xtype: 'button',
					iconCls: 'icon_printer',
					tooltip: Cps.Locale.ReportV2.print,
					handler: function(button, e){
						var grid= button.up('grid');
						grid.print({	
							printCSS: [
								'http://sandboxlounge.com/dev/cps_balance/extjs/resources/css/ext-all.css',
								'http://sandboxlounge.com/dev/cps_balance/extjs/ux/grid/feature/resources/MultiGroupingSummary.css',
								'http://sandboxlounge.com/dev/cps_balance/extjs/ux/grid/plugin/resources/GroupingPanel.css'
							],
							printStyle: true,
							printTitle: 'List',
							printWidth:11,
							printHeight:8.5
							
						});
					}
				},{
					xtype: 'button',
					iconCls: 'icon_excel',
					tooltip: Cps.Locale.ReportV2.exportToExcel,
					handler : function(button, event){
						var grid = button.up('grid');
						grid.downloadExcelXml();
					}
				}
				]
			}
			]
		});

        this.getPanel().removeAll(true);
        this.getPanel().insert(0, grid);
	}
});